package com.ec.rs.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ec.api.client.ElderProfileClient;
import com.ec.api.client.MedicineRecordClient;
import com.ec.api.client.BillClient;
import com.ec.api.domain.dto.CreateBillRequest;
import com.ec.api.domain.po.Bill;
import com.ec.api.domain.po.BillDetail;
import com.ec.api.domain.po.MedicineRecord;
import com.ec.common.domain.Result;
import com.ec.rs.domain.dto.ReviewRequestDTO;
import com.ec.rs.domain.po.Bed;
import com.ec.rs.mapper.CheckInOutRequestMapper;
import com.ec.rs.mapper.BedMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CheckInOutService {

    private final CheckInOutRequestMapper checkInOutRequestMapper;
    private final BedMapper bedMapper;
    private final ElderProfileClient elderProfileClient;
    private final MedicineRecordClient medicineRecordClient;
    private final BillClient billClient;

    /**
     * 处理退住请求并生成账单
     * @return 处理结果
     */
    public boolean handleCheckOutRequest(ReviewRequestDTO dto, Long elderlyUserId, LocalDateTime createdAt) {
        Integer adminId = dto.getApprovedByAdminId();

        // 获取用药记录
        Result<List<MedicineRecord>> medicineResult = medicineRecordClient.getMedicineRecordsByUserId(
            elderlyUserId,
            createdAt.toLocalDate(),
            LocalDate.now()
        );
        if (!medicineResult.success()) {
            return false;
        }
        List<MedicineRecord> medicineRecords = medicineResult.getData();

        // 创建账单
        Bill bill = new Bill();
        bill.setElderlyUserId(elderlyUserId);
        bill.setBillMonth(LocalDate.now().getYear() + "-" + String.format("%02d", LocalDate.now().getMonthValue()));
        bill.setStatus("unpaid");
        bill.setDueDate(LocalDate.now().plusDays(10));
        bill.setCreatedByAdminId(adminId);
        bill.setCreatedAt(LocalDateTime.now());

        // 计算总金额并创建账单详情
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<BillDetail> billDetails = new ArrayList<>();

        // 床位费用
        QueryWrapper<Bed> bedQuery = new QueryWrapper<>();
        bedQuery.eq("occupied_by_user_id", elderlyUserId);
        Bed bed = bedMapper.selectOne(bedQuery);

        if (bed.getCostPerMonth() != null) {
            BillDetail bedDetail = new BillDetail();
            bedDetail.setItemType("accommodation");
            bedDetail.setItemDescription("床位费 (" + bed.getRoomNumber() + "-" + bed.getBedNumber() + ")");
            // 按多少个月计算费用，可能是小数 从createdAt开始到现在
            long months = ChronoUnit.MONTHS.between(createdAt.toLocalDate(), LocalDateTime.now().toLocalDate());
            bedDetail.setAmount(BigDecimal.valueOf(months * bed.getCostPerMonth()));
            bedDetail.setRelatedId(bed.getId().longValue());
            billDetails.add(bedDetail);
            totalAmount = totalAmount.add(bedDetail.getAmount());
        }

        // 用药费用
        for (MedicineRecord record : medicineRecords) {
            BillDetail drugDetail = new BillDetail();
            drugDetail.setItemType("medication");
            drugDetail.setItemDescription("药品: " + record.getDrugName());
            drugDetail.setAmount(BigDecimal.valueOf(record.getCost()));
            drugDetail.setRelatedId(record.getDrugId().longValue());
            billDetails.add(drugDetail);
            totalAmount = totalAmount.add(drugDetail.getAmount());
        }

        bill.setTotalAmount(totalAmount);

        // 6. 调用finance服务保存账单和详情
        CreateBillRequest request = new CreateBillRequest(bill, billDetails);
        Result<Long> billResult = billClient.createBill(request);
        if (!billResult.success()) {
            throw new RuntimeException("账单创建失败: " + billResult.getMsg());
        }

        return true;
    }
}